package com.itheima.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.dto.LoginFormDTO;
import com.itheima.domain.entity.User;
import com.itheima.domain.vo.LoginUserInfo;
import com.itheima.domain.vo.Result;
import com.itheima.mapper.UserMapper;
import com.itheima.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.utils.JwtUtil;
import com.itheima.utils.PhoneCodeUtil;
import com.itheima.utils.ThreadUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-10-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取验证码
     */
    @Override
    public Result getCheckCode(Long phone) {
        //验证手机号的格式
        boolean matches = Pattern.matches("^1[3-9]\\d{9}$", phone.toString());
        if(!matches){
            return Result.fail("手机号格式不正确");
        }
        //随机生成6为验证码并存入redis
        String code = RandomUtil.randomNumbers(6);
        stringRedisTemplate.opsForValue().set("login:code:"+code,code,1, TimeUnit.MINUTES);
        //发送短信验证码
        PhoneCodeUtil.sendPhoneCode(code,phone);
        return Result.ok();
    }

    /**
     * 用户登录
     */
    @Override
    public Result userLogin(LoginFormDTO loginFormDTO) {
        //验证手机号的格式
        boolean matches = Pattern.matches("^1[3-9]\\d{9}$", loginFormDTO.getPhone());
        if(!matches){
            return Result.fail("手机号格式不正确");
        }
        //比对传入的验证码
        String code = stringRedisTemplate.opsForValue().get("login:code:" + loginFormDTO.getCode());
        if(!Objects.equals(code,loginFormDTO.getCode())){
            return Result.fail("验证码不正确或超时");
        }
        //判断是否为新用户
        User user = lambdaQuery().eq(User::getPhone, loginFormDTO.getPhone()).one();
        if(user == null){
            user = User.builder()
                    .phone(loginFormDTO.getPhone())
                    .icon("https://tlias-0626.oss-cn-hangzhou.aliyuncs.com/2025/06/86dff275-7fc9-45a5-b31a-2b97b96ddb39.png")
                    .nickName("user_"+ RandomUtil.randomString(10))
                    .build();
            save(user);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("nickName",user.getNickName());
        map.put("icon",user.getIcon());
        String token = JwtUtil.createJwt(map);
        //token存入redis
        stringRedisTemplate.opsForValue().set("login:token:"+user.getId(),token,4, TimeUnit.HOURS);
        return Result.ok(token);
    }
    /**
     * 查询个人主页
     */
    @Override
    public Result getUserInfo() {
        LoginUserInfo loginUserInfo = ThreadUtil.get();
        return Result.ok(loginUserInfo);
    }
}
